//
// Created by RandBII on 2020/12/27.
//

#ifndef FFMPEGFORANDROID_OPENSLRENDER_H
#define FFMPEGFORANDROID_OPENSLRENDER_H

#include <cstdint>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <queue>
#include <string>
#include <thread>
#include "AudioRender.h"
#include "AudioGLRender.h"

#define MAX_BUFFER_QUEUE_SIZE 3

class OpenSLRender : public AudioRender {

public:
    OpenSLRender() = default;

    virtual  ~OpenSLRender() = default;

    virtual void Init() override;

    virtual void ClearAudioCache() override;

    virtual void RenderAudioFrame(uint8_t *pData, int dataSize) override;

    virtual void UnInit() override;

private:
    int CreateEngine();

    int CreateOutputMixer();

    int CreateAudioPlayer();

    int GetAudioFrameQueueSize();

    void StartRender();

    void HandleAudioFrameQueue();

    static void CreateSLWaitingThread(OpenSLRender *slRender);

    static void AudioPlayerCallback(SLAndroidSimpleBufferQueueItf bufferQueue, void *context);

    SLObjectItf mEngineObj = nullptr;

    SLEngineItf mEngineEngine = nullptr;

    SLObjectItf mOutputMixObj = nullptr;

    SLObjectItf mAudioPlayerObj = nullptr;

    SLPlayItf mAudioPlayerPlay = nullptr;

    SLVolumeItf mAudioPlayerVolume = nullptr;

    SLAndroidSimpleBufferQueueItf mBufferQueue;
    std::queue<AudioFrame *> mAudioFrameQueue;
    std::thread *mThread = nullptr;
    std::mutex mMutex;
    std::condition_variable mCond;
    volatile bool mExit = false;

};


#endif //FFMPEGFORANDROID_OPENSLRENDER_H
